package com.zhentao.filter;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.domain.YdUser;
import com.zhentao.util.Constant;
import com.zhentao.util.JwtUtil;
import com.zhentao.util.ThreadLoadUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class JwtFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String header = request.getHeader(Constant.TOKEN_NAME);
        if (StringUtils.isBlank(header) || JwtUtil.verifyToken(header) == 0) {
            filterChain.doFilter(request, response);
            return;
        }

        Map<String, Object> claimsMap = JwtUtil.getClaimsMap(header);
        Object uid = claimsMap.get("uid");
        Object username = claimsMap.get("username");
        /**
         * 1、ThreadLoadUser.set(username.toString());将当前的username存储到线程中
         * 2、ThreadLoadUser.setId(Long.valueOf(uid.toString()));将当前人id存储到线程中
         */
        ThreadLoadUser.set(username.toString());
        ThreadLoadUser.setId(Long.valueOf(uid.toString()));
        List<String> perms = (List<String>) claimsMap.get("perms");

        YdUser ydUser = new YdUser();
        ydUser.setId(Integer.valueOf(uid.toString()));
        ydUser.setUsername(username.toString());
        ydUser.setPerms(perms);

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(ydUser, null, ydUser.getAuthorities());
        usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        filterChain.doFilter(request, response);


    }
}
